package com.hfy.shop.config;

import constants.RabbitConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ author 韩
 * time: 2024/9/12 16:13
 */

@Slf4j
@Configuration
public class RabbitMQConfig implements ApplicationContextAware {


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取RabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 设置ReturnCallback
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.info("消息发送失败，应答码{}，原因{}，交换机{}，路由键{},消息{}",
                    replyCode, replyText, exchange, routingKey, message.toString());
        });

        // 设置消息发送到交换机(Exchange)回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("【INFO】消息发送到交换机(Exchange)成功, 相关数据: {}", correlationData);
            } else {
                log.error("【ERROR】消息发送到交换机(Exchange)失败, 错误原因: {}, 相关数据: {}", cause, correlationData);
            }
        });

    }


    @Bean
    public DirectExchange delOrderDelayDirectExchange() {
        return ExchangeBuilder
                .directExchange(RabbitConstants.DELAY_ORDER_DEL_DIRECT_EXCHANGE)
                .delayed() // 设置延迟
                .durable(true)
                .build();
    }

    @Bean
    public Queue delOrderDelayQueue() {
        return new Queue(RabbitConstants.DELAY_ORDER_QUEUE);
    }


    @Bean
    public Binding delOrderDelayBinding() {
        return BindingBuilder.bind(delOrderDelayQueue()).to(delOrderDelayDirectExchange()).with(RabbitConstants.DELAY_ORDER_KEY);
    }



}
